package com.atguigu.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.gulimallproduct.service.CategoryBrandRelationService;
import com.atguigu.gulimall.gulimallproduct.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.gulimallproduct.dao.CategoryDao;
import com.atguigu.gulimall.gulimallproduct.entity.CategoryEntity;
import com.atguigu.gulimall.gulimallproduct.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted(Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Comparator.naturalOrder()))
                //Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Comparator.reverseOrder()))
                //Comparator.naturalOrder() 此方法返回一个比较器，该比较器对Comparable对象施加自然排序。
        ).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前菜单是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * @CacheEvict:失效模式
     * 1.同时进行多种缓存操作 @Caching
     * 2.指定删除某个分区下的所有数据 @CacheEvict(value = "category", allEntries = true)
     * 3.sync =  true 解决缓存击穿问题，默认无加锁
     * @param category
     */
//    @Caching( evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 查出所有一级分类数据
     *
     * @return
     *
     */
    /**
     * 1.每一个需要缓存的数据我们都来指定要放到那个名字的缓存【缓存的分区（按照业务类型分）】
     * 2.代表当前方法的结果需要缓存，
     * 3.默认行为
     *  3.1如果缓存中有，方法不用调用。如果缓存中没有，会调用方法，最后将方法的结果放入缓存
     *  3.2key默认自动生成，缓存的名字::SimpleKey[](自主生成的key值)
     *  3.3缓存生成的value值，默认使用jdk序列化机制，将序列化后的数据存到redis
     *  3.4默认ttl时间-1（永不过期）
     *
     *  自定义：
     *  1.指定生成的缓存使用的key     key属性指定，接收一个SpEl表达式
     *  2.指定缓存的数据的存活时间      配置文件中修改ttl(毫秒为单位)
     *  3.将数据保存为json格式
     * */
    @Cacheable(value = {"category"},key = "'level1Categorys'",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<Long, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<Long, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(
                                    l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString()
                            );
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        String s = JSON.toJSONString(parent_cid);
        return parent_cid;
    }

    /**
     * //TODO 产生堆外内存溢出：OutOfDirectMemoryError
     * 1.springboot2.0以后默认使用lettuce作为操作redis客户端，使用netty进行网络通信
     * 2.lettuce的bug导致netty堆外内存溢出 -Xmx300m ;netty如果没有指定堆外内存，默认使用-Xmx300m
     * 可以通过-Dio.netty.maxDirectMemory进行设置
     * ***解决方案：不能使用以上参数只去调大堆外内存
     * 1.升级lettuce客户端   2.切换使用jedis(更新较慢)
     *
     * @return
     */
    public Map<Long, List<Catelog2Vo>> getCatalogJson2() {
        //1.加入缓存逻辑,*****缓存中存的数据都是JSON字符串(JSON跨语言,跨平台兼容)*****

        //从缓存中拿出字符串时应当逆转为能用的对象类型:[序列化与***反序列化***]
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.hasLength(catalogJson)) {
            //2.缓存中没有数据
            Map<Long, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }
        //转为指定对象
        Map<Long, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //1.占分布式锁，去redis占坑
        RLock lock = redisson.getLock("catalogJson-lock");

        Map<Long, List<Catelog2Vo>> dataFromDb = null;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }


        return dataFromDb;

    }

    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //1.占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功，执行业务
            //2.设置过期时间，必须和加锁是同步的，原子性操作
            //redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<Long, List<Catelog2Vo>> dataFromDb = null;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //获取值对比+对比成功后删除锁=原子操作  需要使用到lua脚本解锁
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                //原子性删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                        , Arrays.asList("lock"), uuid);
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)) {
//                //删除我自己的锁
//                redisTemplate.delete("lock");
//            }
            }


            return dataFromDb;
        } else {
            //加锁失败。。。重试
            //休眠100ms重试
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            return getCatalogJsonFromDbWithRedisLock(); //自旋的方式
        }

    }


    private Map<Long, List<Catelog2Vo>> getDataFromDb() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.hasLength(catalogJson)) {
            //如果缓存击中
            Map<Long, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         * 否则开始查询数据库
         * 优化
         * 1.将数据库的多次查询变为一次
         */
        //selectList(queryWrapper:null)查询条件为空则查出所有数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<Long, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(
                                    l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString()
                            );
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJson", s);

        return parent_cid;
    }


    //从数据库查询并封装分类数据
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        //synchronized本地锁，springboot中所有组件都是单实例的
        //TODO 本地锁只能锁住当前进程或方法，在分布式环境下必须使用分布式锁
        synchronized (this) {
            //******得到锁后应该再去缓存中确定一次，如果没有才需要继续查询********（双重检验锁）
            String catalogJson = redisTemplate.opsForValue().get("catalogJson");
            if (StringUtils.hasLength(catalogJson)) {
                Map<Long, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
                });
                return result;
            }
            /**
             * 优化
             * 1.将数据库的多次查询变为一次
             */
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            //1.查出所有1级分类
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
            //2.封装数据
            Map<Long, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
                //1.每一个的一级分类，查到这个一级分类的二级分类
                List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                List<Catelog2Vo> catelog2Vos = null;
                if (categoryEntities != null) {
                    catelog2Vos = categoryEntities.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        //1.找二级分类的三级分类vo封装
                        List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                        if (level3Catelog != null) {
                            //2.封装成指定格式
                            List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(
                                        l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString()
                                );
                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(catelog3Vos);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }
                return catelog2Vos;
            }));

            //3.查到的数据再放入缓存,将对象转为json放在缓存中
            //****查数据库与结果放入缓存应该放在同一把锁内，防止高并发环境下缓存设置短小的延迟导致缓存连续不命中
            String s = JSON.toJSONString(parent_cid);
            redisTemplate.opsForValue().set("catalogJson", s);

            return parent_cid;
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream()
                .filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    public List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }


    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> child = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId())
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted(Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Comparator.naturalOrder()))
        ).collect(Collectors.toList());
        return child;
    }
}